import request from '../../utils/request'
import { useRequest } from 'ahooks'
import { clone } from 'lodash'
import { getStorage } from '../../utils/storage'
export function useFormData({form = {}, formUrl = 'user',backCb,pageInfo  = {}, keyName,setFileList }) {
   const addDataApi = data =>{
       return request({
           url: `/${formUrl}/${ pageInfo.page || 'add' }`,
           method:'POST',
           contentType: data['file'] ?  'multipart/form-data' : null,
           data
       })
   }
   const getFormDetailApi = params => {
       return request({
           url: `/${ formUrl }/queryOne`,
           data: params
       })
   }
   const { loading, run } = useRequest(addDataApi, {
       manual: true,
       onSuccess: res => {
           window.$message.success(res.msg)
           backCb()
       }
   })
    const { loading: viewLoading, run: viewRun } = useRequest(getFormDetailApi, {
        manual: true,
        onSuccess: res => {
            if(res.success && res.data) {
                form.setFieldsValue(res.data)
                if(res.data.hasOwnProperty('cover') && res.data.cover) {
                    form.setFieldValue('file',res.data.cover)
                    setFileList([
                        {
                            status: 'done',
                            url: `${ process.env.NODE_ENV  === 'development' ? process.env.REACT_APP_DEV_API_URL : process.env.REACT_APP_PRO_API_URL }/${ res.data.cover }`
                        }
                    ])
                }
            }
        }
    })
    const handleSave = () => {
        form.validateFields({
            validateOnly: false,
        }).then(_ =>{
           const { province, city } = getStorage('LOCATION_KEY')
           const data = clone(form.getFieldsValue())
            data.status = data.status ? 1 : 0
            data[keyName] = pageInfo.pageKid || null
            data['location'] = province + city
            run(data)
        }).catch(_ =>{})
    }
    const getData = id => {
        let ajaxData = {}
        ajaxData[keyName] = id
        viewRun(ajaxData)
    }
    return {
       loading,
        handleSave,
        getData,
        viewLoading
    }
}
